const { prisma } = require('../config/prisma');
const {
  CONTACT_VIEW_CONFIG_DEFAULTS,
  getDefaultConfigValue,
  getDefaultConfigDescription
} = require('../config/contactViewConfigDefaults');

const reduceDefaultsToObject = () => {
  const defaults = {};
  Object.entries(CONTACT_VIEW_CONFIG_DEFAULTS).forEach(([key, meta]) => {
    defaults[key] = meta.value;
  });
  return defaults;
};

class ContactViewPrisma {
  constructor(data) {
    this.id = data.id;
    this.viewer_id = data.viewer_id;
    this.target_user_id = data.target_user_id;
    this.view_month = data.view_month;
    this.view_count = data.view_count;
    this.free_views_used = data.free_views_used;
    this.paid_views = data.paid_views;
    this.total_cost = data.total_cost;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  /**
   * 获取用户当月查看联系方式的记录
   * @param {number} viewerId 查看者ID
   * @param {number} targetUserId 被查看者ID
   * @param {string} month 月份，格式：YYYY-MM
   * @returns {Promise<ContactViewPrisma|null>}
   */
  static async getMonthlyRecord(viewerId, targetUserId, month) {
    const record = await prisma.contact_view_records.findUnique({
      where: {
        viewer_id_target_user_id_view_month: {
          viewer_id: BigInt(viewerId),
          target_user_id: BigInt(targetUserId),
          view_month: month
        }
      }
    });
    return record ? new ContactViewPrisma(record) : null;
  }

  /**
   * 获取用户当月总查看次数
   * @param {number} viewerId 查看者ID
   * @param {string} month 月份，格式：YYYY-MM
   * @returns {Promise<number>}
   */
  static async getMonthlyViewCount(viewerId, month) {
    const result = await prisma.contact_view_records.aggregate({
      where: {
        viewer_id: BigInt(viewerId),
        view_month: month
      },
      _sum: {
        view_count: true
      }
    });
    return result._sum.view_count || 0;
  }

  /**
   * 记录查看联系方式
   * @param {number} viewerId 查看者ID
   * @param {number} targetUserId 被查看者ID
   * @param {string} month 月份，格式：YYYY-MM
   * @param {boolean} isPaid 是否为付费查看
   * @param {number} cost 费用
   * @returns {Promise<ContactViewPrisma>}
   */
  static async recordView(viewerId, targetUserId, month, isPaid = false, cost = 0) {
    const existingRecord = await ContactViewPrisma.getMonthlyRecord(viewerId, targetUserId, month);
    
    if (existingRecord) {
      // 更新现有记录
      const updateData = {
        view_count: { increment: 1 },
        updated_at: new Date()
      };
      
      if (isPaid) {
        updateData.paid_views = { increment: 1 };
        updateData.total_cost = { increment: cost };
      } else {
        updateData.free_views_used = { increment: 1 };
      }
      
      const updated = await prisma.contact_view_records.update({
        where: {
          viewer_id_target_user_id_view_month: {
            viewer_id: BigInt(viewerId),
            target_user_id: BigInt(targetUserId),
            view_month: month
          }
        },
        data: updateData
      });
      return new ContactViewPrisma(updated);
    } else {
      // 创建新记录
      const newRecord = await prisma.contact_view_records.create({
        data: {
          viewer_id: BigInt(viewerId),
          target_user_id: BigInt(targetUserId),
          view_month: month,
          view_count: 1,
          free_views_used: isPaid ? 0 : 1,
          paid_views: isPaid ? 1 : 0,
          total_cost: cost
        }
      });
      return new ContactViewPrisma(newRecord);
    }
  }

  /**
   * 获取配置值
   * @param {string} key 配置键
   * @returns {Promise<string|null>}
   */
  static async getConfig(key) {
    const config = await prisma.contact_view_config.findUnique({
      where: { config_key: key }
    });
    if (config && config.config_value !== null && config.config_value !== undefined) {
      return config.config_value;
    }
    return getDefaultConfigValue(key);
  }

  /**
   * 获取所有配置
   * @returns {Promise<Object>}
   */
  static async getAllConfigs() {
    const configs = await prisma.contact_view_config.findMany();
    const result = reduceDefaultsToObject();
    configs.forEach(config => {
      result[config.config_key] = config.config_value;
    });
    return result;
  }

  /**
   * 更新配置值
   * @param {string} key 配置键
   * @param {string} value 配置值
   * @returns {Promise<Object>}
   */
  static async updateConfig(key, value) {
    const config = await prisma.contact_view_config.upsert({
      where: { config_key: key },
      update: {
        config_value: value,
        updated_at: new Date()
      },
      create: {
        config_key: key,
        config_value: value,
        description: getDefaultConfigDescription(key) || undefined
      }
    });
    return config;
  }

  /**
   * 批量更新配置
   * @param {Object} configs 配置对象,键值对形式
   * @returns {Promise<Object>}
   */
  static async updateConfigs(configs) {
    const results = {};
    for (const [key, value] of Object.entries(configs)) {
      const updated = await ContactViewPrisma.updateConfig(key, value);
      results[key] = updated.config_value;
    }
    return results;
  }

  /**
   * 获取聊天消息配置（含默认值）
   * @returns {Promise<{chat_message_mode: 'free'|'paid', chat_free_daily_limit: number}>}
   */
  static async getChatMessageConfig() {
    const [modeRaw, limitRaw] = await Promise.all([
      ContactViewPrisma.getConfig('chat_message_mode'),
      ContactViewPrisma.getConfig('chat_free_daily_limit')
    ]);

    const normalizedMode = modeRaw === 'free' ? 'free' : 'paid';
    const fallbackLimit = parseInt(getDefaultConfigValue('chat_free_daily_limit'), 10) || 0;
    const parsedLimit = parseInt(limitRaw, 10);
    const normalizedLimit = Number.isNaN(parsedLimit) ? fallbackLimit : Math.max(0, parsedLimit);

    return {
      chat_message_mode: normalizedMode,
      chat_free_daily_limit: normalizedLimit
    };
  }

  /**
   * 检查用户是否可以免费查看
   * @param {number} viewerId 查看者ID
   * @param {string} month 月份，格式：YYYY-MM
   * @returns {Promise<{canViewFree: boolean, usedFreeViews: number, maxFreeViews: number}>}
   */
  static async checkFreeViewAvailability(viewerId, month) {
    const freeViewsPerMonth = parseInt(await ContactViewPrisma.getConfig('free_views_per_month') || '3');
    const usedFreeViews = await ContactViewPrisma.getMonthlyFreeViewCount(viewerId, month);
    
    return {
      canViewFree: usedFreeViews < freeViewsPerMonth,
      usedFreeViews,
      maxFreeViews: freeViewsPerMonth
    };
  }

  /**
   * 获取用户当月已使用的免费查看次数
   * @param {number} viewerId 查看者ID
   * @param {string} month 月份，格式：YYYY-MM
   * @returns {Promise<number>}
   */
  static async getMonthlyFreeViewCount(viewerId, month) {
    const result = await prisma.contact_view_records.aggregate({
      where: {
        viewer_id: BigInt(viewerId),
        view_month: month
      },
      _sum: {
        free_views_used: true
      }
    });
    return result._sum.free_views_used || 0;
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id.toString(),
      viewer_id: this.viewer_id.toString(),
      target_user_id: this.target_user_id.toString(),
      view_month: this.view_month,
      view_count: this.view_count,
      free_views_used: this.free_views_used,
      paid_views: this.paid_views,
      total_cost: parseFloat(this.total_cost),
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = ContactViewPrisma;
